package com.linyaonan.com.nio.selector.tcp.blocking_io;

import lombok.Cleanup;
import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author: Lin
 * @date: 2020/11/15
 */
public class Server {

    @SneakyThrows
    public static void main(String[] args) {
        @Cleanup ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 1.绑定
        serverSocketChannel.socket().bind(new InetSocketAddress(8888));
        // 2. 接受客户端连接
        @Cleanup SocketChannel socketChannel = serverSocketChannel.accept();
        // 3. 设置缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(128);
        // 4. 写入缓冲区
        while (socketChannel.read(buffer) != -1) {
            buffer.flip();
            byte[] bytes = new byte[buffer.limit()];
            buffer.get(bytes);
            // 5. 输出结果
            System.out.println(new String(bytes));
            // 6. 清空缓冲区
            buffer.clear();
        }
    }
}
